<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Jobs\MessageJobs;
use App\Models\FormIds;
use App\Models\Templates;
use App\Models\Tmplmsgs;
use App\Models\TmplmsgsLog;
use App\Models\Users;
use App\Models\Videos;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Overtrue\Socialite\User;
use Symfony\Component\Cache\Simple\RedisCache;

class TmplmsgController extends Controller
{

    /**
     * 获取 模板消息_列表
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function index()
    {
        try {
            $app = app('wechat.mini_program');
            $predis = app('redis')->connection()->client();
            $cache = new RedisCache($predis);
            $app->rebind('cache', $cache);
            $data = $app->template_message->getTemplates(0, 20);
            if ($data['errcode'] == 0 && $data['errmsg'] == 'ok') {
                foreach ($data['list'] as &$item) {
                    $content = explode('}}', $item['content']);
                    $keyword = array();
                    $keywordText = [];
                    foreach ($content as $val) {
                        $keyword[] = trim(substr($val, strpos($val, "{{") + 2, -5));
                        $keywordText[] = trim(substr($val, 0, strpos($val, "{{")));
                    }
                    $form = [];
                    $item['page'] = '';
                    //获取数据库对应关键词的值，进行填充返回
                    $keywordForDB = Tmplmsgs::where('template_id', $item['template_id'])->first();
                    if (!$keywordForDB) {
                        //模板ID不存在，创建
                        foreach ($keyword as $word) {
                            if ($word) {
                                $form[$word] = '';
                            }
                        }
                        $createData = [
                            'template_id' => $item['template_id'],
                            'keyword' => [$form],
                            'title' => $item['title'],
                        ];
                        Tmplmsgs::create($createData);
                    } else {
                        $form = $keywordForDB['keyword'];
                        $item['page'] = $keywordForDB['page'];
                        $item['emphasis'] = $keywordForDB['emphasis'];
                    }
                    $item['form'] = $form;
                    $item['keyword'] = array_filter($keyword);
                    $item['keyword_text_arr'] = array_combine($item['keyword'], array_filter($keywordText));
                    $item['keyword_text'] = implode(',', array_filter($keywordText));
                }
                return $this->returnJson(0, '', $data['list']);
            }
            return $this->returnJson(1, $data['errmsg']);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }


    /**
     * 更新模板消息
     * @return \Illuminate\Http\JsonResponse
     */
    public function update()
    {
        $data = request()->all();
        if ($data['template_id']) {
            $keywordForDB = Tmplmsgs::where('template_id', $data['template_id'])->first();
            $keywordForDB->update($data);
            //更新缓存
            cache()->tags('template')->forever($data['template_id'], $data);
            return $this->returnJson(0, '更新成功');
        }
        return $this->returnJson(1, '参数错误');
    }

    /**
     * 推送模板消息
     * @return \Illuminate\Http\JsonResponse
     */
    public function push()
    {
        $template_id = (string)request('id', '');
        if (!$template_id) {
            return $this->returnJson(1, '模板消息推送失败');
        }
        //推送前先删除所有过期的formid信息
        FormIds::where('expires_at','<=',Carbon::now())->delete();

        //根据模板ID获取推送信息
        $templateInfo = Tmplmsgs::where('template_id', $template_id)->first();

        if (!$templateInfo) {
            return $this->returnJson(1, '模板消息数据不存在');
        }

        //生成推送记录
        $tmplmsgsLog = TmplmsgsLog::where('template_id',$template_id)
            ->whereDate('created_at',Carbon::now()->toDateString())
            ->first();
        if(!$tmplmsgsLog){
            $tmplmsgsLogData = [
                'title' => $templateInfo['title'],
                'template_id' => $templateInfo['template_id'],
                'number' => 0,
                'total' => 0
            ];
            TmplmsgsLog::create($tmplmsgsLogData);
        }
        dispatch((new MessageJobs($templateInfo))->onQueue('daduizhang_message'));
        return $this->returnJson(0, '推送成功');
    }

    public function token(){
        $app = app('wechat.mini_program');
        $predis = app('redis')->connection()->client();
        $cache = new RedisCache($predis);
        $app->rebind('cache', $cache);
        $accessToken = $app->access_token;
        $token = $accessToken->getToken(true); // 强制重新从微信服务器获取 token.
        return $this->returnJson(0, '重新生成access_token成功',$token);
    }


//    public function push(){
//        $message = FormIds::select('formid')->where('openid','oOM3i5JgHG9zFGZW8e87CKJK4gMs')
//            ->where('expires_at','>',Carbon::now()->addHours(1))
//            ->first();
//        if($message) {
//            $sendData = [
//                'touser' => 'oOM3i5JgHG9zFGZW8e87CKJK4gMs',
//                'template_id' => $template_id,
//                'page' => $templateInfo['page'],
//                'form_id' => $message['formid'],
//                'data' => $templateInfo['keyword'][0],
//                'emphasis_keyword' => isset($templateInfo['emphasis']) ? $templateInfo['emphasis'] . ".DATA" : '',
//            ];
//            //小程序实例化
//            $app = app('wechat.mini_program');
//            $predis = app('redis')->connection()->client();
//            $cache = new RedisCache($predis);
//            $app->rebind('cache', $cache);
//            $data = $app->template_message->send($sendData);
//            return $this->returnJson(0, '推送成功', $data);
//        }
//    }


}
